/* eslint-disable @typescript-eslint/ban-ts-comment */
import { defineComponent, PropType, ref, toRefs, watch } from 'vue'
/* components */
import FormCascader from '@src/component/form/components/FormCascader/FormCascader.vue'
/* const */
import { ConnectorFetchAppModulesStorageKey, ConnectorFormCascadeDataSourceType, ConnectorGetModuleListParams, CreateConnectorModalFields, useConnectorCardSettingFetchModuleList } from '@src/modules/connector';
import Field from '@model/entity/Field';
import StorageModuleEnum from '@model/enum/StorageModuleEnum';
import { ComponentEmitAction } from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/model/enum/action';
/* utils */
import { addConnectorModuleUniqueIdEveryLevel, connectorAppModuleToFormCascaderDataSource } from '@src/modules/connector/util';
import { addComponentNamePrefix } from '@src/util/component';
import Log from '@src/util/log';
import { storageRm } from '@src/util/storage.ts';
import { t } from '@src/locales';
import { cloneDeep } from 'lodash';
import { DataType } from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/model/enum/data';

type ComponentType = `${DataType}`

export type FormConnectorDataRuleSettingDataSourceProps = {
    fromBizTypeId: string,
    value: string [],
    isCreated: boolean,
    placeholder: string,
    type: ComponentType
}

export type FieldUpdateResult = {
  field: Field;
  newValue: any; 
  oldValue: any;
  selectItem: any
}

export default defineComponent({
  props: {
    fromBizTypeId: {
      type: String as PropType<string>,
      default: '',
    },
    value: {
      type: Array as PropType< string[]>,
      default: ()=> []
    },
    isCreated: {
      type: Boolean as PropType<boolean>,
      default: ()=> false
    },
    placeholder: {
      type: String as PropType<string>,
      default: ()=> t('common.connector.fieldSetting.dataSourcesPlaceholder')
    },
    type: {
      type: String as PropType<ComponentType>,
      default: ()=> DataType.Connector
    },
    // 来自的页面类型
    fromPageType: {
      type: String as PropType<string>,
      default: ()=> ''
    }
  },
  components: {
    [addComponentNamePrefix(FormCascader.name)]: FormCascader
  },
  emits: [ ComponentEmitAction.Input ],
  setup(props: FormConnectorDataRuleSettingDataSourceProps, { emit }) {
    const { fromBizTypeId, value, isCreated, placeholder, type } = toRefs(props)
    // paas 关联应用
    const { loading: fetchModuleListLoading, moduleList, fetchModuleList, fetchTriggerModuleItemList, moduleTriggerListItem } = useConnectorCardSettingFetchModuleList(props.fromPageType)
    const { loading: fetchModuleListItemLoading, fetchModuleItemList, moduleListItem } = useConnectorCardSettingFetchModuleList()
    const relationAppFormField = ref(cloneDeep(CreateConnectorModalFields.slice(0, 1)[0]))
    const currentCascaderItem = ref(null)
    const publinkFormCascader = ref(null)

    const dataSource = ref<ConnectorFormCascadeDataSourceType []>([])

    const initialize = () => {
      return new Promise((resolve, reject)=> {
        const params: ConnectorGetModuleListParams = { 
          fromBizTypeId: fromBizTypeId.value, 
        }
  
        try {
          fetchModuleList(params).then(result => {
            
            const filterDataSource = connectorAppModuleToFormCascaderDataSource(result)
            resolve(filterDataSource)
              
            try {
                
              dataSource.value = filterDataSource
                
            } catch (error) {
                
              Log.error(error, initialize.name)
                
            }
              
          })
        } catch (error) {
          reject(error)
        }
      
      })
    }
    
    const attrs = {
      props: {
        propsV2: {
          expandTrigger: 'click',
          value: 'value',
          label: 'label',
          checkStrictly: true,
          children: 'test', // 修改children的key不是children通过手动加载
          lazy: true,
          async lazyLoad (node: Record<string, any>, resolve: (arg0: any) => void) {
            const { level, data } = node;
       
            // 当在第二层级的时候去加载另一个接口获取对应的列表
            if(level === 2) {

              type.value === DataType.Connector 
                ? await fetchModuleItemList({ appId: data?.appId || '' }) 
                : await fetchTriggerModuleItemList({ appId: data?.appId || '', direction: 'from' })
              const addUniqueIdDataList = addConnectorModuleUniqueIdEveryLevel( type.value === DataType.Connector ? moduleListItem.value : moduleTriggerListItem.value, false)
              return resolve(connectorAppModuleToFormCascaderDataSource(addUniqueIdDataList, true))
            } 

            // 第一层直接加载value
            if(level === 0) {
              await initialize()
              return resolve(dataSource.value)
            }

            // 第二次层加载children
            if(level === 1 || level >= 3) {
              return resolve(data.children);
            }

            resolve(node)
          }
        }
      },
      scopedSlots:{
        default: ({node, data}: Record<string, any>)=> {
          const appLevel = node.level === 1 || node.level === 2
          return (
            data 
              ? <span 
                // class={ !data.canSelect && !appLevel ? 'el-cascader-panel-item__label-disabled' : 'el-cascader-panel-item__label'} 
                class='el-cascader-panel-item__label'
                onClick={(e: MouseEvent)=> handleCascaderItemClick(e, {node, data})}>
                { data.label }
              </span> 
              : null
          )
        }
      }   
    }

    const handleCascaderItemClick = (e: MouseEvent, { node, data }: Record<string, any>) => {
    // 这里判断是否是倒数第二级的可选
      if(data?.canSelect) {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        const target = e.target.parentNode.previousElementSibling
        target.click()
        currentCascaderItem.value = data
        const cascaderRef = (publinkFormCascader.value as unknown as any)?.$children[0];
        cascaderRef.$nextTick(()=> cascaderRef.dropDownVisible = false)
      }

      if(type.value === DataType.Connector) {
        // 选择完清除对应的缓存
        storageRm(StorageModuleEnum.Connector, ConnectorFetchAppModulesStorageKey)
      }
    }

    const update = ({ field, newValue }: FieldUpdateResult) => {
      emit(ComponentEmitAction.Input, { field, newValue, selectItem: newValue.length ? currentCascaderItem.value : {} })
    }

    watch(()=> isCreated.value, (n)=> {
      // @ts-ignore
      relationAppFormField.value.disabled = n
    }, {
      immediate: true
    })

    return ()=> (
      <publink-form-cascader
        ref={publinkFormCascader}
        popperClass="connector-module-create-connector-name__cascader"
        placeholder={placeholder.value}
        version="new"
        field={relationAppFormField.value}
        value={value.value}
        onUpdate={update}
        {...attrs}
      >
      </publink-form-cascader>
    )
  }
})